<?php
class User
{
    public $user_id;
    public $data = array(); // user data
    public $toUpdate = null;


    public $RecipesController = null;
    public $PlantsController  = null;
    public $InventoryController  = null;

    function  __construct($uid) {
        $this->user_id = $uid;
        $this->RecipesController = new RecipesController($this);
        $this->PlantsController = new PlantsController($this);
        $this->InventoryController = new InventoryController($this);
    }

    // is registered? then fetch row
    public function is_registered()
    {
        $query = 'SELECT * FROM `players` WHERE `user_id`='.$this->user_id;
        $data =_database::torow($query);
        if(is_array($data) && $data['user_id'])
        {
            $this->data = $data;
            return $data;
        }
        return false;
    }

    public function setProperty($name,$value)
    {
        if(isset($this->data[$name]) && ($this->data[$name] === $value))
        {
            return false;
        }
        $this->data[$name] = $value;
        $this->toUpdate[$name] = $value;
        return true;
    }

    public function save()
    {
        if(is_array($this->toUpdate))
        {
            $sql = null;
            $this->toUpdate["lastSave"] = rpc::$time;
            foreach($this->toUpdate as $f => $v)
            {
                $sql[] = '`'.$f.'`=\''.mysql_escape_string($v).'\'';
            }

            $query = 'UPDATE `players` SET '.implode(',',$sql).' WHERE `user_id`='.$this->user_id;
            
            $r = _database::query($query);
            if($r)
            {
                $this->toUpdate = null;
            }
        }
    }
}
?>
